package com.weharvest.edu.controller;

import com.weharvest.edu.config.ProjectConfig;
import com.weharvest.edu.constant.CookieConstant;
import com.weharvest.edu.constant.RedisConstant;
import com.weharvest.edu.dto.BackstageUserDTO;
import com.weharvest.edu.entity.BackstageUser;
import com.weharvest.edu.enums.WechatExceptionEnum;
import com.weharvest.edu.exception.WechatException;
import com.weharvest.edu.service.BackstageUserService;
import com.weharvest.edu.utlis.CookieUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


/**
 * 后台开发平台配置
 */
@Controller
@RequestMapping("/admin/wechat")
@Slf4j
public class WechatController {

    @Resource
    private WxMpService wxOpenService;

    @Resource
    private ProjectConfig projectConfig;


    @GetMapping("/login")
    public ModelAndView  login(){
        return  new ModelAndView("edu/common/error");
    }

    @Resource
    private BackstageUserService backstageUserService;


    @Resource
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 后台用户登录授权
     * @param resultUrl
     * @return
     */
    @GetMapping("/qrAuthorize")
    public String  qrAuthorize(@RequestParam(value = "resultUrl",
            defaultValue ="http://sanly.mynatapp.cc/weharvest/edu/index")
                                       String resultUrl) {
        //重定向的地址  会微信回调地址前缀要一样
        String url = projectConfig.getOpenAuthorizeUrl()+"/weharvest/wechat/qrUserInfo";
        String redirectUrl="";
        try {
            redirectUrl = wxOpenService.buildQrConnectUrl(url,
                    WxConsts.QrConnectScope.SNSAPI_LOGIN, URLEncoder.encode(resultUrl,"UTF-8"));
        } catch (Exception e) {
            log.error("[发起微信开放授权],{}", e);
            throw new WechatException(WechatExceptionEnum.OPEN_ENCODE_ERROR);
        }
        return "redirect:"+redirectUrl;
    }

    /**
     * 扫描后返回用户信息
     * @param code
     * @param resultUrl
     * @param response
     * @return
     */
    @GetMapping("/qrUserInfo")
    public ModelAndView qrUserInfo(@RequestParam("code")String code ,
                                   @RequestParam("state")String resultUrl,
                                   HttpServletResponse response) {
        //根据code获取accesstoken
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken =new WxMpOAuth2AccessToken();
        try {
            wxMpOAuth2AccessToken=wxOpenService.oauth2getAccessToken(code);
        }catch (Exception e){
            log.error("[返回微信开放授权],{}",e);
            throw  new  WechatException(WechatExceptionEnum.OPEN_ACCESSTOKEN_ERROR);
        }
        String openid=wxMpOAuth2AccessToken.getOpenId();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("[微信登录]用户openid:{"+openid+"},登录时间:{"+sdf.format(new Date())+"}");
        //查询是否管理员
        BackstageUserDTO backstageUserDTO=new BackstageUserDTO();
        backstageUserDTO.setOpenid(openid);
        BackstageUser backstageUser=backstageUserService.findByBackstageOpenid(backstageUserDTO);
        if(null ==backstageUser){
            //返回错误页面
            Map<String,Object> map=new HashMap<>();
            map.put("msg","对不起！您不是管理员");
            map.put("url",projectConfig.getOpenAuthorizeUrl()+"/weharvest/wechat/qrAuthorize");
            return new ModelAndView("common/error",map);
        }
        String token = UUID.randomUUID().toString();
        //设置redis
        stringRedisTemplate.opsForValue().set(
                String.format(RedisConstant.TOKEN,token),
                openid,
                RedisConstant.EXPIRE,
                TimeUnit.SECONDS);
        //设置cooklie
        CookieUtil.set(response, String.format(CookieConstant.TOKEN,token),token,7200);
        return  new ModelAndView("redirect:"+resultUrl+"?openid="+openid);
    }

}
